from odoo import models, api


class SbProductCategory(models.Model):
    _inherit = 'product.category'

    def cron_all(self):
        records = self.env['product.category'].sudo().search([])
        for rec in records:
            rec.categ_upload_mes()

    @api.model_create_multi
    def create(self, vals_list):
        result = super().create(vals_list)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            for rec in result:
                rec.with_delay().categ_upload_mes()
        return result

    def write(self, vals):
        res = super().write(vals)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            self.with_delay().categ_upload_mes()
        return res

    def categ_upload_mes(self):
        """
        产品分类上传 MES 系统
        BS_MTRL_TYPE
        """
        category_list = []
        for record in self:
            category_list.append({
                "org_id": "0001",  # 组织编码
                "mtype_code": record.code if record.code else None,  # 物料分类编码
                "mtype_name": record.name,  # 物料分类名称
                "is_valid": "Y",  # 启用状态 N:未启用 Y:已启用
                "remark": record.notes or '0'  # 备注
            })
        data = {
            "docType": "BS_MTRL_TYPE",  # 文档类型
            "updateType": "UPDATE",  # 更新类型
            "data": category_list
        }
        self.env['s.mes.upload'].upload_data(data=data)
